package com.centaline.androidsalesblog.activities.sale;

import android.content.Intent;
import android.text.TextUtils;

import com.android.volley.VolleyError;
import com.baidu.location.BDLocation;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.model.LatLng;
import com.centaline.androidsalesblog.R;
import com.centaline.androidsalesblog.adapter.EsfEstateAdapter;
import com.centaline.androidsalesblog.api.sale.EsfEstateListApi;
import com.centaline.androidsalesblog.application.MyLocation;
import com.centaline.androidsalesblog.base.BaseActivity;
import com.centaline.androidsalesblog.constants.AppConstant;
import com.centaline.androidsalesblog.constants.CommonConstant;
import com.centaline.androidsalesblog.constants.ExtraConstant;
import com.centaline.androidsalesblog.iml.DropCompleteListener;
import com.centaline.androidsalesblog.model.businissobject.DropBo;
import com.centaline.androidsalesblog.model.databaseobject.EsfEstateDo;
import com.centaline.androidsalesblog.model.responseobject.EsfEstateListRo;
import com.centaline.androidsalesblog.rx.database.DropSaleRegionFunc1;
import com.centaline.androidsalesblog.rx.database.MetroFunc1;
import com.centaline.androidsalesblog.rx.database.RxDataBase;
import com.centaline.androidsalesblog.rx.database.SearchDataFunc1;
import com.centaline.androidsalesblog.rx.map.RxMap;
import com.centaline.androidsalesblog.utils.DropUtil;
import com.centaline.androidsalesblog.widgets.MRecyclerView;
import com.centaline.androidsalesblog.widgets.dropdown.DropDownView;
import com.centaline.androidsalesblog.widgets.dropdown.SalePriceDrop;
import com.centaline.androidsalesblog.widgets.dropdown.SingleDrop;
import com.centaline.androidsalesblog.widgets.dropdown.TrebleDrop;
import com.centanet.framework.glide.GlideLoad;
import com.centanet.framework.interfaces.IRecycleViewListener;
import com.centanet.framework.interfaces.IResponseListener;
import com.trello.rxlifecycle.ActivityEvent;

import java.util.ArrayList;
import java.util.Locale;

import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func3;
import rx.schedulers.Schedulers;

/**
 * 周边同价位小区
 * Created by guilin on 16/5/2.
 */
public class EsfEstateListOfPriceActivity extends BaseActivity {

    private DropDownView dropDownView;
    private MRecyclerView mRecyclerView;

    private TrebleDrop trebleDrop;
    private SalePriceDrop salePriceDrop;
    private SingleDrop singleDrop;

    private ArrayList<EsfEstateDo> esfEstateDos = new ArrayList<>();
    private EsfEstateAdapter esfEstateAdapter;
    private EsfEstateListApi esfEstateListApi;
    private int iRefreshType;
    private LocationClient locationClient;
    private boolean needLocation;

    @Override
    protected int setLayoutId() {
        return R.layout.activity_esf_estate_list_of_price;
    }

    @Override
    protected void findViews() {
        setUniversalToolbar(R.string.title_esf_of_nearby);
        dropDownView = (DropDownView) findViewById(R.id.dropDownView);
        mRecyclerView = (MRecyclerView) findViewById(R.id.mRecyclerView);
    }

    @Override
    protected void initViews() {
        dropDownView.initTabs(R.array.esfEstate);
        trebleDrop = new TrebleDrop(dropDownView, this);
        salePriceDrop = new SalePriceDrop(dropDownView, this);
        singleDrop = new SingleDrop(dropDownView, this);
        dropDownView.addDrops(trebleDrop, salePriceDrop, singleDrop);
        dropDownView.setDropCompleteListener(new DropCompleteListener() {
            @Override
            public void complete(int position, boolean fromMore, int type, DropBo... dropBos) {
                int size = dropBos == null ? 0 : dropBos.length;
                switch (type) {
                    case 10://区域
                        esfEstateListApi.reset();
                        esfEstateListApi.setType("R");
                        if (size == 1) {
                            if (DropUtil.compareValue(dropBos[0])) {
                                resetTab(position);
                                setTab(position, "区域");
                            } else {
                                esfEstateListApi.setScopeId(dropBos[0].getValue());
                                setTab(position, dropBos[0].getText());
                            }
                            downRefresh(false);
                        } else if (size == 2) {
                            esfEstateListApi.setScopeId(dropBos[0].getValue());
                            if (DropUtil.compareValue(dropBos[1])) {
                                setTab(position, dropBos[0].getText());
                            } else {
                                esfEstateListApi.setScopeId(dropBos[1].getValue());
                                setTab(position, dropBos[1].getText());
                            }
                            downRefresh(false);
                        }
                        break;
                    case 11://附近
                        esfEstateListApi.reset();
                        esfEstateListApi.setType("F");
                        if (size == 2) {
                            esfEstateListApi.setRound(dropBos[1].getValue());
                            setTab(position, dropBos[1].getText());
                            downRefresh(true);
                        }
                        break;
                    case 20://地铁
                        esfEstateListApi.reset();
                        esfEstateListApi.setType("S");
                        if (size == 1) {
                            if (DropUtil.compareValue(dropBos[0])) {
                                resetTab(position);
                                setTab(position, "地铁");
                            } else {
                                esfEstateListApi.setSubwayid(dropBos[0].getValue());
                                setTab(position, dropBos[0].getText());
                            }
                            downRefresh(false);
                        } else if (size == 2) {
                            esfEstateListApi.setSubwayid(dropBos[0].getValue());
                            if (DropUtil.compareValue(dropBos[1])) {
                                setTab(position, dropBos[0].getText());
                            } else {
                                esfEstateListApi.setStationid(dropBos[1].getValue());
                                setTab(position, dropBos[1].getText());
                            }
                            downRefresh(false);
                        }
                        break;
                    case 30://均价
                        if (size == 1) {
                            String value = dropBos[0].getValue();
                            if (TextUtils.isEmpty(value)) {
                                esfEstateListApi.setMin("");
                                esfEstateListApi.setMax("");
                                resetTab(position);
                                downRefresh(false);
                            } else if (value.contains(",")) {
                                String[] values = value.split(",");
                                esfEstateListApi.setMin(values[0]);
                                esfEstateListApi.setMax(values[1]);
                                setTab(position, dropBos[0].getText());
                                downRefresh(false);
                            }
                        } else if (size == 2) {
                            esfEstateListApi.setMin(dropBos[0].getValue());
                            esfEstateListApi.setMax(dropBos[1].getValue());
                            setTab(position, DropUtil.customPrice(dropBos[0], dropBos[1]));
                            downRefresh(false);
                        }
                        break;
                    case 100://排序
                        if (size == 1) {
                            if (TextUtils.isEmpty(dropBos[0].getValue())) {
                                esfEstateListApi.setSort("");
                                resetTab(position);
                            } else {
                                esfEstateListApi.setSort(dropBos[0].getValue());
                                setTab(position, dropBos[0].getText());
                            }
                            downRefresh(false);
                        }
                        break;
                    default:
                        break;
                }
            }
        });
        Observable.combineLatest(RxDataBase.getSaleRegions()
                        .subscribeOn(Schedulers.io())
                        .map(new DropSaleRegionFunc1()),
                RxDataBase.nearby(),
                RxDataBase.getMetro()
                        .subscribeOn(Schedulers.io())
                        .map(new MetroFunc1()),
                new Func3<ArrayList<DropBo>, DropBo, ArrayList<DropBo>, ArrayList<DropBo>>() {
                    @Override
                    public ArrayList<DropBo> call(ArrayList<DropBo> dropBos, DropBo nearBy, ArrayList<DropBo> dropBos3) {
                        final ArrayList<DropBo> list = new ArrayList<>();
                        DropBo dropBo = new DropBo(10);
                        dropBo.setText("区域");
                        dropBo.setValue(CommonConstant.DROP_VALUE_NULL);
                        dropBo.setChildrenList(new ArrayList<DropBo>());
                        DropBo dropBo1 = new DropBo(10);
                        dropBo1.setText(CommonConstant.DROP_TEXT_NO_LIMITED);
                        dropBo1.setValue(CommonConstant.DROP_VALUE_NULL);
                        dropBo.getChildrenList().add(dropBo1);
                        if (AppConstant.NearbyEnable) {
                            dropBo.getChildrenList().add(nearBy);
                        }
                        dropBo.getChildrenList().addAll(dropBos);
                        list.add(dropBo);
                        dropBo = new DropBo(20);
                        dropBo.setText("地铁");
                        dropBo.setValue(CommonConstant.DROP_VALUE_NULL);
                        dropBo.setChildrenList(dropBos3);
                        list.add(dropBo);
                        return list;
                    }
                }).observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<ArrayList<DropBo>>() {
                    @Override
                    public void call(ArrayList<DropBo> dropBos) {
                        trebleDrop.init(dropBos);
                    }
                });
        RxDataBase.getSearchData("AvgPrice")
                .map(new SearchDataFunc1(30))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<ArrayList<DropBo>>() {
                    @Override
                    public void call(ArrayList<DropBo> dropBos) {
                        salePriceDrop.init(dropBos);
                    }
                });
        ArrayList<DropBo> orderBy = new ArrayList<>();
        DropBo dropBo = new DropBo(100);
        dropBo.setText("智能排序");
        dropBo.setValue("");
        orderBy.add(dropBo);
        dropBo = new DropBo(100);
        dropBo.setText("均价从低到高");
        dropBo.setValue("2");
        orderBy.add(dropBo);
        dropBo = new DropBo(100);
        dropBo.setText("均价从高到低");
        dropBo.setValue("3");
        orderBy.add(dropBo);
        singleDrop.init(orderBy);

        mRecyclerView.setIRecycleViewListener(new IRecycleViewListener() {
            @Override
            public void downRefresh() {
                iRefreshType = 1;
                esfEstateListApi.setStartIndex(0);
                if (needLocation) {
                    locationClient.start();
                } else {
                    request();
                }
            }

            @Override
            public void upRefresh() {
                iRefreshType = 2;
                esfEstateListApi.setStartIndex(esfEstateDos.size());
                request();
            }

            @Override
            public void onItemClick(int position) {
                startActivity(new Intent(EsfEstateListOfPriceActivity.this, EsfEstateDetailActivity.class)
                        .putExtra(ExtraConstant.CestCode, esfEstateDos.get(position).getCestCode()));
            }
        });

        esfEstateAdapter = new EsfEstateAdapter(this, GlideLoad.init(this), esfEstateDos);
        mRecyclerView.setAdapter(esfEstateAdapter);

        esfEstateListApi = new EsfEstateListApi(EsfEstateDetailActivity.class,
                EsfEstateListRo.class,
                new IResponseListener<EsfEstateListRo>() {
                    @Override
                    public void onResponse(EsfEstateListRo esfEstateListRo) {
                        ArrayList<EsfEstateDo> temp = esfEstateListRo.getList();
                        if (iRefreshType == 1)
                            esfEstateDos.clear();
                        if (temp == null) {
                            mRecyclerView.stopRefresh(false);
                        } else {
                            esfEstateDos.addAll(temp);
                            mRecyclerView.stopRefresh(temp.size() == 10);
                        }
                        if (esfEstateListApi.getStartIndex() == 0) {
                            snack(esfEstateListRo.getTotal() == 0 ?
                                    getString(R.string.snack_esf_nothing) :
                                    String.format(Locale.CHINA, getString(R.string.snack_esf), esfEstateListRo.getTotal()));
                        }
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {
                        mRecyclerView.refreshError();
                    }
                });
        esfEstateListApi.setPosttype("s");
        LatLng latLng = getIntent().getParcelableExtra(ExtraConstant.LatLng);
        double avgPrice = getIntent().getDoubleExtra(ExtraConstant.Price, 0);

        if (latLng != null &&
                latLng.latitude != 0 &&
                latLng.longitude != 0) {
            esfEstateListApi.setLatLng(latLng);
            esfEstateListApi.setType("F");
            esfEstateListApi.setRound("1000");
            setTab(0, "1km");
        }
        if (avgPrice > 0) {
            esfEstateListApi.setMin(String.format(Locale.CHINA, "%.0f", avgPrice * 0.9));
            esfEstateListApi.setMax(String.format(Locale.CHINA, "%.0f", avgPrice * 1.1));
            salePriceDrop.setMaxAndMin(String.format(Locale.CHINA, "%.1f", avgPrice * 1.1 / 10000),
                    String.format(Locale.CHINA, "%.1f", avgPrice * 0.9 / 10000));
            if (avgPrice * 0.9 > 10000) {
                setTab(1, String.format(Locale.CHINA, "%s-%s",
                        String.format(Locale.CHINA, "%.1f", avgPrice * 0.9 / 10000),
                        String.format(Locale.CHINA, "%.1f万", avgPrice * 1.1 / 10000)));
            } else if (avgPrice * 1.1 < 10000) {
                setTab(1, String.format(Locale.CHINA, "%s-%s",
                        String.format(Locale.CHINA, "%.0f", avgPrice * 0.9),
                        String.format(Locale.CHINA, "%.0f元", avgPrice * 1.1)));
            } else {
                setTab(1, String.format(Locale.CHINA, "%s-%s",
                        String.format(Locale.CHINA, "%.0f元", avgPrice * 0.9),
                        String.format(Locale.CHINA, "%.1f万", avgPrice * 1.1 / 10000)));
            }
        }

        locationClient = MyLocation.getLocationClient();
        RxMap.location(locationClient, false)
                .compose(this.<BDLocation>bindUntilEvent(ActivityEvent.DESTROY))
                .subscribe(new Action1<BDLocation>() {
                    @Override
                    public void call(BDLocation bdLocation) {
                        switch (bdLocation.getLocType()) {
                            case 61:
                            case 161:
                                LatLng latLng = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
                                esfEstateAdapter.setLocation(latLng);
                                esfEstateListApi.setLatLng(latLng);
                                request();
                                break;
                            default:
                                esfEstateAdapter.setLocation(null);
                                esfEstateListApi.setLatLng(null);
                                esfEstateListApi.setRound("");
                                break;
                        }
                    }
                });

        mRecyclerView.startRefresh();
    }

    private void downRefresh(boolean needLocation) {
        this.needLocation = needLocation;
        mRecyclerView.startRefresh();
    }

    private void request() {
        esfEstateListApi.startRequest();
    }

    /**
     * 重置标签
     *
     * @param position 位置
     */
    private void resetTab(int position) {
        dropDownView.resetTab(position);
    }

    /**
     * 设置标签
     *
     * @param position 位置
     * @param tab      文本
     */
    protected void setTab(int position, String tab) {
        dropDownView.setTab(position, tab);
    }
}
